import { observable, action } from 'mobx';
import * as Api from '../../api/calendar';
import { ListPage, BrowserHrm, RouteLayout, SelectPage } from 'weaver-mobile-page';
import { Tools } from 'weaver-mobile';

import CreateStore from '../create/createStore';
const jq = require('../../util/jquery') ;
const getLabel = Tools.getLabel;

export default class CalendarStore {
  @observable createStore = new CreateStore();
  @observable conditionsList = [];
  @observable conditionsInfo = []; 
  @observable allconditionsList = [];
  @observable allconditionsInfo = [];
  @observable userID = '';
  @observable userName = '';
  @observable currentUserID = '';
  @observable isall = '';
  @observable list = new ListPage.Store();
  @observable listUnderling = new ListPage.Store();
  @observable listAttention = new ListPage.Store();
  @observable browser = new BrowserHrm.Store({route: '/calendar/myFllow'})
  @observable selectDate = ''; //日历上选择的日期
  @observable hrmLayout = new RouteLayout.Store({route: '/calendar', id:'schedule'})
  @observable appointLayout = new RouteLayout.Store({route: '/calendar/allCalendar', id:'appointhrm'})
  @observable btnAddDisabled = false;
  @observable hrmBrowser = new BrowserHrm.Store({route: '/calendar/allCalendar',id: 'appointhrm'});
  @observable weekStart = 0;
  @observable mysubVisible = false;
  @observable selectType1 = new SelectPage.Store({route: '/calendar/myCalendar/schdulesync'});
  @observable selectType2 = new SelectPage.Store({route: '/calendar/myCalendar/schdulesync'});
  @observable selectSysnc1 = new SelectPage.Store({route: '/calendar/myCalendar/schdulesync'});
  @observable selectSysnc2 = new SelectPage.Store({route: '/calendar/myCalendar/schdulesync'});
  @observable OAtoLocal = 2;
  @observable autoToserver = 0;
  @observable autoTomobile = 0;
  @observable toOAscheduleTypes = [];
  @observable mobileCalendar = [];
  @observable toServerCalendars = [];
  @observable toMobilescheduleTypes = [];
  @observable typeOptions = [];
  @observable calendarOptions = []; //{key: '1',showname: '1111'},{key: '2',showname: '1112'},{key: '3',showname: '1113'},
  @observable syncState = false;
  @observable starttime = '';
  @observable endtime = '';
  @observable isrun = false;
  @observable voiceString = '';
  @observable continueSpeech = false; // 校验是否存在jaApi
  @observable stopVoice = false;
  @observable yesVoice = false;
  @observable voiceSuccess = true; // 是否开启语音功能
  @observable yesChangeVoice = false;
  @observable yewStopVoice = false;
  @observable voiceContent = '';
  @observable siriVisible = 'block';
  @observable orVoice = false;
  //目的:日历组件不是受控组件,只有在第一次渲染的时候才有效果,第一次render的时候没有走接口取得正常的值,所以加这个来进行判断
  @observable isInit= false;
  @observable semanticStatus = false; // 判断是否支持语音接口
  @observable itemCardHeight = 100;
  @observable syncLoading = false;
  @observable tabPanes  = [];
  @observable pageNum = '1';
  @observable totalpageNum = '1';
  @observable searchStr = '';
  @observable tabs = [
    { title: getLabel(18480,'我的日程'),key:1 },
    { title: getLabel(386548,'下属日程'),key:2 },
    { title: getLabel(26469,'我的关注'),key:3 },
    { title: getLabel(27910,'所有日程'),key:4 }
  ];
  @observable freshCalendar = () => {};
  // @action
  // setTabs = (tabs=[])=>{
  //   if(tabs.length){
  //     tabs.forEach((item,index)=>{
  //       this.tabs.forEach((item1,index1)=>{
  //         if(item1.key==item){
  //           this.tabs.splice(index1,1)
  //         }
  //       })
  //     })
  //   }
  // }
  @action
  setState1 = (params = {}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
  }
  
  @action 
  getTabPanes = ()=>{
    let tabArray = [];
    let tempTabs = [];
    let pathArr = [];
    let i = 1;
    if(!this.tabs && localStorage.getItem('WPBaseTabs')){
      tempTabs = JSON.parse(localStorage.getItem('WPBaseTabs'))
      return tempTabs;
    }else{
      pathArr.push('')
      this.tabs.forEach((item,index)=>{
        if(item.title==getLabel(18480,'我的日程')){
          tabArray.push( { title: getLabel(18480,'我的日程'),key:'myCalendar', path: '/calendar/myCalendar'  });
          pathArr.push('/calendar/myCalendar');
          i++;
        }
        if(item.title==getLabel(386548,'下属日程')){
          tabArray.push( { title: getLabel(386548,'下属日程'),key:'subordinate', path: '/calendar/subordinate' });
          pathArr.push('/calendar/subordinate');
          i++;
        }
        if(item.title==getLabel(26469,'我的关注')){
            tabArray.push( { title: getLabel(26469,'我的关注'),key:'myFllow', path: '/calendar/myFllow' });
          pathArr.push('/calendar/myFllow')
          i++;
        }
        if(item.title==getLabel(27910,'所有日程')){
          tabArray.push( { title: getLabel(27910,'所有日程'),key:'allCalendar', path: '/calendar/allCalendar' });
          pathArr.push('/calendar/allCalendar')
          i++;
        }
      })
      if(localStorage){
        if(tabArray.length>0){
          localStorage.setItem('WPBaseTabs',JSON.stringify(tabArray))
          localStorage.setItem('WPTabpath',JSON.stringify(pathArr))
        }
      }
      this.tabPanes = tabArray;
    }
     
  }

  @action 
  // 我的日程
  getMyWorkplanDatas = (params) => {
    const { isCalendar } = params;
    Api.getMyWorkplanDatas(params).then((res) => {
      if(isCalendar === '0') {
        this.conditionsList = res.mobileEvents;
      }else{
        this.conditionsInfo = res.mobileEvents;
        this.weekStart = res.weekStartDay;
        this.isInit = true;
      }
      
    });
  }
  // 所有日程
  getAllWorkplanDatas = (params) => {
    const { isCalendar } = params;
    Api.getAllWorkplanDatas(params).then((res) => {
      if(isCalendar === '0') {
        this.allconditionsList = res.mobileEvents
      }else{
        this.allconditionsInfo = res.mobileEvents;
        this.weekStart = res.weekStartDay;
        this.isInit = true;
      }
      
    });
  }

  // 删除日程列表中的数据，防止删除日程后请求接口过慢导致，再次可以点击已被删除的日程，致使无权限打开日程
  deleteWorkplanStoreList = (id) => {
    let tab = localStorage.workplanTabs;

    const deleteList = (list) => {
      let storeList = [];
      list && list.map(item => {
        if(item.id !== id) {
          storeList.push(item);
        }
        return '';
      });
      return storeList;
    } 
    if(tab === '1' || tab === 1) {
      // 我的日程下
      this.conditionsList = deleteList(this.conditionsList);
    }
    if(tab === '4' || tab === 4) {
      // 所有日程下
      this.allconditionsList = deleteList(this.allconditionsList);
    }
  }

  // 我的关注
  getAttentionData = (params, type) => {
    Api.getAttentionData(params).then((res) => {
      if(params.pageNum) {
        this.pageNum = parseInt(params.pageNum) + 1;
      }
      if(type === 'searchMyFllow') { //有条件搜索需清空历史数据
        this.listAttention = new ListPage.Store();
      }
      this.list.setState(res);
      this.listAttention.setState(res);
      this.totalpageNum = res.totalpage;
    });
  }
  // 我的下属
  getUnderlining = (params) => {
    params = {...params}
    Api.getUnderlining(params).then((res) => {
      this.list.setState(res);
      this.listUnderling.setState(res)
    });
  }

  // 添加关注
  addAttention = (params, callback) => {
    Api.addAttention(params).then((res) => {
      this.btnAddDisabled = false;
      this.list.setState(res);
      // this.listAttention.setState(res);
      typeof(callback) === 'function' && callback();
    });
  }
  // 取消关注
  deleteMyFollow = (params, callback) => {
    Api.delAttention(params).then((res) => {
      this.list.setState(res);
      // this.listAttention.setState(res);
      typeof(callback) === 'function' && callback();
    });
  }

  changeUserInfo = (userid, username) => {
    this.userID = userid;
    this.userName = username;
  }

  setState = (params = {},callback) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    this.yesVoice && typeof(callback) === 'function' && callback()
  }

  synctoMobile = (scheduletype,mobilecalendar,callback) => {
    // oa同步到手机
    // this.getSyncSetting('set','');
    window.em && window.em.checkJsApi('synctoMobile') &&  window.em.synctoMobile({
      syncUrl:'/api/workplan/base/getWorkPlanList',
      updateAppIdUrl:'/api/workplan/base/updateAppWPId',//插入或更新日程对应关系
      starttime: this.starttime,//yyyy-MM-dd HH:mm:ss所有日程相关的时间都yyyy-MM-dd HH:mm:ss
      endtime: this.endtime,
      ec_id: window.localStorage.emobile_ec_id,//ecology服务端标识
      scheduleTypes: scheduletype,//日程类型
      mobileCalendar: mobilecalendar,//本地日历名称
      auto:this.autoTomobile,
      version: '1',
      success: function () {
          // app调syncUrl去拉日程数据，
          callback({syncState: true});//同步成功
          // Toast.loading('同步完成',1);
          this.getMyWorkplanDatas();
      },
      fail: function() {
        // Toast.loading('同步失败',1);
      }
    });
  }

  synctoServer = (mobilecalendar,scheduletype,callback) => {
    // 本地同步到oa
    window.em && window.em.checkJsApi('synctoServer') && window.em.synctoServer({
      syncUrl:'/api/workplan/base/getWorkPlanList',//当前页面的相对地址即可
      addUrl:'/api/workplan/base/createBySynMobile',//创建日程的接口地址
      editUrl:'/api/workplan/base/editBySynMobile',//编辑日程的接口地址
      delUrl:'/api/workplan/base/deleteBySynMobile',//删除日程的接口地址
      updateAppIdUrl:'/api/workplan/base/updateAppWPId',//插入或更新日程对应关系
      starttime: this.starttime,//
      endtime: this.endtime,
      ec_id: window.localStorage.emobile_ec_id,//ecology服务端标识
      scheduleTypes: scheduletype,//日程类型
      mobileCalendar: mobilecalendar,//本地日历名称
      auto: 1,//    |int | 是否自动同步 0 否 1是    |
      version: '1',
      success: function () {
          // app调syncUrl去拉日程数据，
          callback({syncState: true});//同步成功
          // Toast.loading('同步完成',1);
          this.getMyWorkplanDatas();
      },
      fail: function() {
        // Toast.loading('同步失败',1);
      }
    });
  }

  getSyncSetting = (type,callback,toOA, toMobile, mobilecalendar, serverCalendars) => {
    let _this = this;
    window.em && window.em.checkJsApi('getSyncSetting') && window.em.getSyncSetting({
      operation: type,
      ec_id:window.localStorage.emobile_ec_id,//标识
      syncUrl:'/api/workplan/base/getWorkPlanList',//当前页面的相对地址即可
      addUrl:'/api/workplan/base/createBySynMobile',//创建日程的接口地址
      editUrl:'/api/workplan/base/editBySynMobile',//编辑日程的接口地址
      delUrl:'/api/workplan/base/deleteBySynMobile',//删除日程的接口地址
      updateAppIdUrl:'/api/workplan/base/updateAppWPId',//插入或更新日程对应关系
      autoToserver:  this.autoToserver,
      autoTomobile:  this.autoTomobile,
      toOAscheduleTypes: toOA,
      toMobilescheduleTypes: toMobile,
      mobileCalendar: mobilecalendar,// 服务端同步到本地日历名称
      toServerCalendars: serverCalendars, // 本地日历同步到服务端
      version: '1',
      success: function (res) {
        //获取客户端自动同步设置状态
          _this.autoToserver = res.autoToserver;
          _this.autoTomobile = res.autoTomobile;
          _this.toOAscheduleTypes = res.toOAscheduleTypes || []; // 本地同步到oa-保存为日程类型
          _this.toServerCalendars = res.toServerCalendars || []; // 本地同步到oa-选择类型
          _this.toMobilescheduleTypes = res.toMobilescheduleTypes || [];
          _this.mobileCalendar = res.mobileCalendar || []; //oa同步到本地-服务端数据同步到本地哪个日历中
          // _this.setState({autoToserver: res.autoToserver,autoTomobile: res.autoTomobile});
      },
    });
  }

  getMobileCalendars = (callback, callback1) => {
    let arr = [];
    let _this = this;
    this.syncLoading = true;
    if(window.em) {
      window.em && window.em.checkJsApi('getMobileCalendars') && window.em.getMobileCalendars({
        success: function (res) {
            //获取客户端的日历列表
            let resJSON = JSON.stringify(res.calendars).split('[')[1].split(']')[0];
            resJSON.split(',').map((item,i) => {
              let obj = {
                key: i+'',
                showname: item.split('"')[1],
              }
              arr.push(obj);
              return '';
            });
            // _this.syncLoading = false;
            typeof callback === 'function' && callback({calendarOptions: arr});
            typeof callback1 === 'function' && callback1(); 
          }
        });
      }
    
  }

  getWorkPlanType = (params,callback) => {
    // 同步日程类型
    Api.getWorkPlanType(params).then(res => {
      if(res && res.workPlanType) {
        this.typeOptions = res.workPlanType.options;
        callback();
      }
    })
  }

  getSemanticStatus = (params) => {
    // 检测是否有语音新建日程接口
    Api.getSemanticStatus(params).then(res => {
      if (res.api_status) {
        this.semanticStatus = res.semanticStatus && false; // 暂时写死测试
      }
    })
  }
  
  // 语音-请求跨域所需参数
  getSemanticUrlAndParam = (param, callback) => {
    let params = {
      content: param
    };
    Api.getSemanticUrlAndParam(params).then(res => {
      if (res && res.api_status) {
        // this.crossDomain = {
        //   ...this.crossDomain,
        //   params: JSON.parse(res.params),
        //   url: res.url
        // }
        let corsparams = {};
        if (res.params && res.url) {
          corsparams = {
            datas: {...JSON.parse(res.params)},
            url: res.url
          };
        }
        this.getCORS(corsparams, callback);
      }
    });
  }

  // 跨域请求
  getCORS = (params, callback) => {
    let _this = this;
    jq.ajax({
      type: "get",
      url: params.url,
      dataType: "json",
      data: params.datas,
      success: function(res) {
          let datas = res.data;
          let param = {
            jsonContent: JSON.stringify(datas),
          };
          if (res && res.isSuccess) {
             _this.createStore.addByWord && _this.createStore.addByWord('', callback, param); 
          }
      }
    });
  }

}